import time, requests, json, re
from frame_work.browser_engine import BrowserEngine
from page_object.quantity_page import QuantityPage
from frame_work.logger import Logger
# 导入NoSuchElementException
from selenium.common.exceptions import NoSuchElementException
from frame_work.setting import *
from frame_work.yaml_file import YAML
from frame_work.read_config import global_config

logger = Logger(__name__).get_logger()


# def pay_quantity():
#     pay_form_url = 'http://user.sk1.com/seller/tryings/get_pay_from/70000539/?_=1682493762471'
#     header = {
#         'Cookie': 'PHPSESSID = bg215o7i7niqq96cgkd5rvlh05;shikee = user0637%7C2%7CCHNY0fa26246fLpIjpll0TpEQTulexHzdd6FMWd%2FrlKaXftxY3Xvj%2BUKdjuU4Q%3D%3D'
#     }
#     res = requests.get(pay_form_url, headers=header).text
#     print(res)

class PayQuantity(object):

    def __init__(self, session):
        self.session = session
        # self.driver = None
        self.browser = BrowserEngine()
        self.yaml = YAML(os.path.join(base_Dir, 'data', 'data.yaml'))
        # self.driver = browser.open_browser()

    def get_cookies_info(self, domain='shikee'):
        """
        通过传递过来的session获取cookies
        :return:
        """
        if domain == 'taotaofa':
            domain_add = self.yaml.get_data('tfx_domain') + '.cn'
        else:
            domain_add = self.yaml.get_data('domain') + '.com'
        cookies_dict = {'domain': '.' + domain_add,
                        'name': '',
                        'value': '',
                        'path': '/',
                        'httpOnly': True,
                        'secure': False}
        # print(self.session.cookies.items())
        for c_name, c_value in self.session.cookies.items():
            if c_name == domain:
                cookies_dict.update({"name": c_name, "value": c_value})
        return cookies_dict

    # def pay_quantity(self, tid):
    #     """
    #     支付活动款,统一用余额支付接口
    #     :param tid:
    #     :return:
    #     """
    #     # 请求支付表单地址,获取活动支付表单数据1
    #     pay_form_url = 'http://user.sk1.com/seller/tryings/get_pay_from/'+str(tid)+'/?_=1682493762471'
    #     pay_form_str = self.session.get(pay_form_url).text
    #     print(json.loads(pay_form_str).get('data'))
    #     form_value = json.loads(pay_form_str).get('data')
    #
    #     # 生成交易数据Trade/pay
    #     trade_pay_url = 'https://api0.hlzf3.com/Trade/pay'
    #     data = {}
    #     data.update({'site': re.findall('name="site" value="(.*?)"', form_value)[0]})
    #     data.update({'serviceType': re.findall('name="serviceType" value="(.*?)"', form_value)[0]})
    #     data.update({'uid': re.findall('name="uid" value="(.*?)"', form_value)[0]})
    #     data.update({'type': re.findall('name="type" value="(.*?)"', form_value)[0]})
    #     data.update({'tradetype': re.findall('name="tradetype" value="(.*?)"', form_value)[0]})
    #     data.update({'tid': re.findall('name="tid" value="(.*?)"', form_value)[0]})
    #     data.update({'tradeNo': re.findall('name="tradeNo" value="(.*?)"', form_value)[0]})
    #     data.update({'goodsTitle': re.findall('name="goodsTitle" value="(.*?)"', form_value)[0]})
    #     data.update({'guaranteetitle': re.findall('name="guaranteetitle" value="(.*?)"', form_value)[0]})
    #     data.update({'servicetitle': re.findall('name="servicetitle" value="(.*?)"', form_value)[0]})
    #     data.update({'guaranteeOrder': re.findall('name="guaranteeOrder" value="(.*?)"', form_value)[0]})
    #     data.update({'serviceOrder': re.findall('name="serviceOrder" value="(.*?)"', form_value)[0]})
    #     data.update({'guaranteeMoney': re.findall('name="guaranteeMoney" value="(.*?)"', form_value)[0]})
    #     data.update({'serviceMoney': re.findall('name="serviceMoney" value="(.*?)"', form_value)[0]})
    #     data.update({'key': re.findall('name="key" value="(.*?)"', form_value)[0]})
    #     data.update({'notifyurl': re.findall('name="notifyurl" value="(.*?)"', form_value)[0]})
    #     data.update({'backurl': re.findall('name="backurl" value="(.*?)"', form_value)[0]})
    #     data.update({'extFee': re.findall('name="extFee" value="(.*?)"', form_value)[0]})
    #     data.update({'temp1': re.findall('name="temp1" value="(.*?)"', form_value)[0]})
    #     data.update({'temp2': re.findall('name="temp2" value="(.*?)"', form_value)[0]})
    #     data.update({'temp3': re.findall('name="temp3" value="(.*?)"', form_value)[0]})
    #     # trade_pay_res = self.session.post(trade_pay_url, data=data, verify=False).text
    #
    #     # 检查登录状态1
    #     checklogin_url = 'https://api0.hlzf3.com/Trade/checklogin'
    #     checklogin_res = self.session.post(checklogin_url, data=data, verify=False).text
    #     sign = re.findall('name="sign" value="(.*?)"', checklogin_res)[0] # 响应提取sign
    #     # postdata = re.findall('name="postdata" value="(.*?)"', checklogin_res)[0] # 响应提取postdata
    #
    #     # 交易数据确认
    #     # data.update({"postdata": postdata, 'sign': sign})
    #     # payment_nx_str = self.session.post('https://api0.hlzf3.com/Trade/payment_nx', data=data, verify=False)
    #
    #     # 交易密码弹框确认
    #     # check_password_form = 'https://api0.hlzf3.com/Trade/CheckPassword?sign=' + sign + '&type=1'
    #     # res01 = self.session.get(check_password_form, verify=False).text
    #
    #     # 输入密码,确认支付1
    #     pay_data = {}
    #     pay_data.update({'sign': sign, "action": "1", "type": "1", "password": "111111"})
    #     pay_res = self.session.post('https://api0.hlzf3.com/Trade/CheckPassword', data=pay_data, allow_redirects=False, verify=False)
    #     # headers = pay_res.history
    #     # href="/Trade/CheckPay?sign=3085776638b243b568030e3a33c9988d">here
    #     sign_url = re.findall('href="(.*?)"', pay_res.text)[0]  # 响应提取sign
    #
    #     # print(f'获取第一次重定向的headers头部信息：{headers[0].headers}')
    #     # print(f'获取重定向最终的url：{headers[len(headers) - 1].headers["location"]}')
    #     # location = headers[len(headers) - 1].headers["location"]  # /Trade/CheckPay?sign=6fc697f27e7ca1b5ce8604321b0ea940
    #     paysign = sign_url.split('=')[-1]   # 响应中提取支付sign
    #
    #     # 确认支付
    #     # check_pay_url = 'https://api0.hlzf3.com'+sign_url
    #     # check_pay_res = self.session.get(check_pay_url, verify=False).text
    #
    #     # 确认支付结果
    #     pay_result_url = 'https://api0.hlzf3.com/Trade/PayResult'
    #     data.update({'paysign': paysign})
    #     # data.pop('sign')
    #     # data.pop('postdata')
    #     pay_result_res = self.session.post(pay_result_url, data=data, allow_redirects=False, verify=False)
    #
    #     # 回调通知
    #     # pay_back_res = self.session.post('http://user.sk1.com/seller/tryings/pay_back/'+str(tid)).text
    #     # print(pay_back_res)

    def pay_quantity(self, tid):
        """
        支付活动款,统一用余额支付接口
        :param tid:
        :return:
        """
        # 请求支付表单地址,获取活动支付表单数据
        pay_form_url = 'http://user.sk1.com/seller/tryings/get_pay_from/'+str(tid)+'/?_=1682493762471'
        pay_form_str = self.session.get(pay_form_url).text
        print(json.loads(pay_form_str).get('data'))
        form_value = json.loads(pay_form_str).get('data')

        # 检查登录状态
        data = {}
        data.update({'site': re.findall('name="site" value="(.*?)"', form_value)[0]})
        data.update({'serviceType': re.findall('name="serviceType" value="(.*?)"', form_value)[0]})
        data.update({'uid': re.findall('name="uid" value="(.*?)"', form_value)[0]})
        data.update({'type': re.findall('name="type" value="(.*?)"', form_value)[0]})
        data.update({'tradetype': re.findall('name="tradetype" value="(.*?)"', form_value)[0]})
        data.update({'tid': re.findall('name="tid" value="(.*?)"', form_value)[0]})
        data.update({'tradeNo': re.findall('name="tradeNo" value="(.*?)"', form_value)[0]})
        data.update({'goodsTitle': re.findall('name="goodsTitle" value="(.*?)"', form_value)[0]})
        data.update({'guaranteetitle': re.findall('name="guaranteetitle" value="(.*?)"', form_value)[0]})
        data.update({'servicetitle': re.findall('name="servicetitle" value="(.*?)"', form_value)[0]})
        data.update({'guaranteeOrder': re.findall('name="guaranteeOrder" value="(.*?)"', form_value)[0]})
        data.update({'serviceOrder': re.findall('name="serviceOrder" value="(.*?)"', form_value)[0]})
        data.update({'guaranteeMoney': re.findall('name="guaranteeMoney" value="(.*?)"', form_value)[0]})
        data.update({'serviceMoney': re.findall('name="serviceMoney" value="(.*?)"', form_value)[0]})
        data.update({'key': re.findall('name="key" value="(.*?)"', form_value)[0]})
        data.update({'notifyurl': re.findall('name="notifyurl" value="(.*?)"', form_value)[0]})
        data.update({'backurl': re.findall('name="backurl" value="(.*?)"', form_value)[0]})
        data.update({'extFee': re.findall('name="extFee" value="(.*?)"', form_value)[0]})
        data.update({'temp1': re.findall('name="temp1" value="(.*?)"', form_value)[0]})
        data.update({'temp2': re.findall('name="temp2" value="(.*?)"', form_value)[0]})
        data.update({'temp3': re.findall('name="temp3" value="(.*?)"', form_value)[0]})
        checklogin_url = 'https://api0.hlzf3.com/Trade/checklogin'
        checklogin_res = self.session.post(checklogin_url, data=data, verify=False).text
        sign = re.findall('name="sign" value="(.*?)"', checklogin_res)[0] # 响应提取sign

        # 输入密码,确认支付
        pay_data = {}
        pay_data.update({'sign': sign, "action": "1", "type": "1", "password": "111111"})
        pay_res = self.session.post('https://api0.hlzf3.com/Trade/CheckPassword', data=pay_data, allow_redirects=False, verify=False)
        sign_url = re.findall('href="(.*?)"', pay_res.text)[0]  # 响应提取sign
        paysign = sign_url.split('=')[-1]   # 响应中提取支付sign

        # 确认支付结果
        pay_result_url = 'https://api0.hlzf3.com/Trade/PayResult'
        data.update({'paysign': paysign})
        pay_result_res = self.session.post(pay_result_url, data=data, allow_redirects=False, verify=False)

        # 回调通知
        # pay_back_res = self.session.post('http://user.sk1.com/seller/tryings/pay_back/'+str(tid)).text
        # print(pay_back_res)


    def test_pay_quantity(self, tid, source="shikee"):
        """
        通过add_cookies方法不用再次登录，直接无界面支付活动款
        :param tid:
        :return:
        """
        # print('开始')
        if source == 'taotaofa':
            pay_entrance_url = self.yaml.get_data(
                'tfx_pay')['url'] + '/' + str(tid) + '/1'
        elif source == 'modshow':
            pay_entrance_url = self.yaml.get_data(
                'modshow_pay')['url'] + '/' + str(tid) + '/1'
        else:
            pay_entrance_url = self.yaml.get_data(
                'pay')['url'] + '/' + str(tid) + '/1'
        self.driver = self.browser.open_browser()
        logger.debug("开始支付活动")
        self.pay_Page = QuantityPage(self.driver)
        self.driver.get(pay_entrance_url)
        if source == 'taotaofa':
            cookies_dict = self.get_cookies_info('taotaofa')
        else:
            cookies_dict = self.get_cookies_info()
        # 对cookie进行操作
        self.pay_Page.cookie("add", **cookies_dict)
        logger.debug("跳转到:%s" % pay_entrance_url)
        self.driver.get(pay_entrance_url)
        if source == 'taotaofa':
            self.pay_Page.tfx_click_pay_btn()
        else:
            self.pay_Page.click_pay_btn()
        # 显示等待支付页面元素加载完
        if source == 'taotaofa':
            self.pay_Page.tfx_wait_pay_title(8)
        else:
            self.pay_Page.wait_pay_title(8)
        logger.debug("跳转到互联支付，地址: %s" % self.driver.current_url)
        self.pay_Page.switch_password_frame(0)
        # 不确定用户支付密码哪个正确,config.ini配置多个密码,循环读取并判断
        pay_pwd = global_config.get_pwd('payPwd')
        pay_pwd = pay_pwd.split(',')
        for pwd in pay_pwd:
            self.pay_Page.input_password(pwd)
            self.pay_Page.click_confirm()
            time.sleep(2)
            text = self.pay_Page.get_error_tips()
            if not text:  # 输入密码没有错误提示,说明密码正确
                logger.debug("支付密码%s正确" % pwd)
            logger.debug("密码错误:%s 现在执行下一个密码校验" % text)
        time.sleep(2)
        logger.debug("回跳到联盟支付成功页面，地址: %s" % self.driver.current_url)
        # logger.debug("跳转的页面标题:%s" % self.driver.title)
        pay_back_url = self.driver.current_url
        value = pay_back_url.split('/')[-1]

        # value = self.pay_Page.get_success_tips()
        # logger.debug("活动支付结束")
        self.check_result(value, tid)
        # print('结束')

    def check_result(self, value, tid):
        logger.debug("开始比对成功结果")
        try:
            if value != tid:
                raise Exception("不是支付成功页面,比对结果不一致！")
        except Exception as e:
            logger.info(
                "tid: %s 支付失败,可能互联环境不稳定 或者 配置的支付密码都不对导致 Reason : %s" %
                (tid, e))
        else:
            logger.info("tid: %s 支付成功" % (tid))
        finally:
            self.driver.quit()

    # def __del__(self):
    #     self.driver.quit()


if __name__ == '__main__':
    # suite = unittest.TestLoader().loadTestsFromTestCase(PayQuantity)
    # runner=unittest.TextTestRunner()
    # runner.run(suite)
    # pay = PayQuantity('user0626')
    # # pay.test_pay_quantity(4949622)
    # pay_quantity()
    pass
